﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.Net.Security;
using System.ComponentModel;

namespace UtilityLibrary.Http
{
	public class ThumbprintCertModel : ICertModel
	{
		private X509Certificate2 _cert;
		/// <summary>
		/// 证书
		/// </summary>
		public X509Certificate2 Cert { get { return _cert; } }

		/// <summary>
		/// 验证证书事件
		/// </summary>
		public event EventHandler<CancelEventArgs> OnCheckValidationResult;

		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="thumbprint"></param>
		public ThumbprintCertModel(String thumbprint)
		{
			CertCreater.GetCertByThumbprint(thumbprint);
		}

		public void SetCert(System.Net.HttpWebRequest request)
		{
			//添加证书
			if (_cert != null)
			{
				ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
				request.ClientCertificates.Add(_cert);
			}
		}

		/// <summary>
		/// 证书相关，安全策略模式
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="certificate"></param>
		/// <param name="chain"></param>
		/// <param name="errors"></param>
		/// <returns></returns>
		private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
		{
			//通过委托事件来处理验证证书过程
			CancelEventArgs args = new CancelEventArgs();
			if (OnCheckValidationResult != null) OnCheckValidationResult(this, new CancelEventArgs());
			return !args.Cancel;
		}
	}
}
